//
//  MoreCommitViewController.m
//  Findif
//
//  Created by Mac on 2019/3/20.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "MoreCommitViewController.h"
#import "SquareTableViewCell.h"
#import "SquareHeadrerView.h"
#import "TopicCommitModel.h"
#import "SquareCommitModel.h"
#import "SquareCommitTableViewCell.h"
#import "MoreCommitTableViewCell.h"
#import "PersonalViewController.h"

@interface MoreCommitViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,MoreCommitTableViewCellDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, weak)UITextField * textField;
@property (nonatomic, weak)UIButton * sendButton;
@property (nonatomic, strong)NSArray <TopicCommitModel *> * listArray;
@property (nonatomic, strong)TopicCommitModel * fatherModel;
@property (nonatomic, copy)NSString * pid;

@end

@implementation MoreCommitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
//    if (self.ID) {
//
//       self.pid = self.ID;
//    }
    
    
    [self loadData];
    [self setupUI];
}


- (void)loadData{
    
    if (self.ID) {
        
        [[ZRNetworkTool sharedTool] getDynamicCommentsInfoWithDynamic_id:self.ID WithBlock:^(BOOL success, id responseData) {
            
//                    NSLog(@"res===%@",responseData);
            if (success) {
                
                NSDictionary * dict = responseData[@"data"];
                
                self.fatherModel = [TopicCommitModel yy_modelWithDictionary:dict[@"father"]];
                self.listArray = [NSArray yy_modelArrayWithClass:[TopicCommitModel class] json:dict[@"child"]];
            }
            
        }];
    }else if (self.topicID){
        
        [[ZRNetworkTool sharedTool] getTopicCommentInfoWithTopic_id:self.topicID WithBlock:^(BOOL success, id responseData) {
            
//            NSLog(@"res===%@",responseData);
            
            if (success) {
                
                NSDictionary * dict = responseData[@"data"];
                
                self.fatherModel = [TopicCommitModel yy_modelWithDictionary:dict[@"father"]];
                self.listArray = [NSArray yy_modelArrayWithClass:[TopicCommitModel class] json:dict[@"child"]];
                
            }
        }];
    }

    
    
}

- (void)setFatherModel:(TopicCommitModel *)fatherModel{
    
    _fatherModel = fatherModel;
    
    self.title = fatherModel.user_name;
    self.pid = [NSString stringWithFormat:@"%@",fatherModel.id];
    
    [self.tableView reloadData];
}


- (void)setListArray:(NSArray<TopicCommitModel *> *)listArray{
    
    _listArray = listArray;
    
    [self.tableView reloadData];
}

- (void)setupUI{

    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - topHeight - 65 * SCREENH6)];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
    //    tableView.rowHeight = 124 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;

    self.tableView = tableView;

    [self.tableView registerClass:[MoreCommitTableViewCell class] forCellReuseIdentifier:@"MoreCommitTableViewCell"];
    [self.tableView registerClass:[SquareCommitTableViewCell class] forCellReuseIdentifier:@"MoreSquareCommitTableViewCell"];
    [self.tableView registerClass:[SquareHeadrerView class] forHeaderFooterViewReuseIdentifier:@"MoreSquareDatailHeadrerView"];

    [self.view addSubview:self.tableView];


    UIView * bottomView = [UIView new];

    bottomView.backgroundColor = ZRWhiteColor;
    bottomView.userInteractionEnabled = YES;

    self.bottomView = bottomView;

    [self.view addSubview:self.bottomView];


    UITextField * textFiled = [[UITextField alloc] init];

    textFiled.borderStyle = UITextBorderStyleRoundedRect;
    textFiled.backgroundColor = ColorWithRGB(0xE0E0E0);
    textFiled.returnKeyType = UIReturnKeyDone;
    //    textFiled.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    textFiled.tintColor = ZRBlackColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x909090);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:14 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"我来说两句~" attributes:attrs];
    textFiled.textColor = ZRBlackColor;
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14 * SCREENH6];
    textFiled.delegate = self;

    self.textField = textFiled;

    [self.bottomView addSubview:self.textField];


    UIButton * sendButton = [UIButton new];

    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(clickSendButton) forControlEvents:UIControlEventTouchUpInside];
    sendButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    sendButton.backgroundColor = ZRBlackColor;
    sendButton.layer.cornerRadius = 5 * SCREENH6;
    sendButton.layer.masksToBounds = YES;

    self.sendButton = sendButton;

    [self.bottomView addSubview:self.sendButton];
}

- (void)viewDidLayoutSubviews{

    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(-kBarHeight);
        make.height.mas_equalTo(60 * SCREENH6);
        make.leading.trailing.mas_equalTo(self.view);
    }];

    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.bottomView).offset(15 * SCREENH6);
        make.centerY.mas_equalTo(self.bottomView);
        make.width.mas_equalTo(295 * SCREENH6);
        make.height.mas_equalTo(30 * SCREENH6);
    }];

    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.bottomView).offset(-15 * SCREENH6);
        make.leading.mas_equalTo(self.textField.mas_trailing).offset(8 * SCREENH6);
        make.centerY.mas_equalTo(self.textField);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        
        return 1;
    }else{
        
        return self.listArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        
        SquareCommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MoreSquareCommitTableViewCell" forIndexPath:indexPath];
        cell.topicModel = self.fatherModel;
        return cell;
    }else{
        
        MoreCommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MoreCommitTableViewCell" forIndexPath:indexPath];
        cell.model = self.listArray[indexPath.row];
        cell.delegate = self;
        return cell;
    }
    
    
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.section == 0) {
        // 使用缓存行高，避免计算多次
        return self.fatherModel.rowHeight;
    }else{

        TopicCommitModel * model = self.listArray[indexPath.row];

        return model.rowHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    if (section == 0) {

        return 43 * SCREENH6;
    }else{

        return 0;
    }

}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    if (section == 0) {

        SquareHeadrerView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MoreSquareDatailHeadrerView"];

        header.string = @"全部评论";
        return header;
    }else{

        return nil;
    }

}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{

    if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
        ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF4F5F6);
    }

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        TopicCommitModel * model = self.listArray[indexPath.row];
        self.pid = [NSString stringWithFormat:@"%@",model.id];
        
        NSString * user_name = [NSString stringWithFormat:@"%@",model.user_name];
        self.textField.placeholder = [NSString stringWithFormat:@"回复:%@",user_name];
        
        [self.textField becomeFirstResponder];
    }
    
}


- (void)clickSendButton{

    if (self.ID) {
        
        if (self.textField.text.length > 0) {
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            
            [dict setValue:self.fatherModel.dynamic_id forKey:@"dynamic_id"];
            [dict setValue:self.textField.text forKey:@"content"];
            [dict setValue:self.pid forKey:@"pid"];
            
            [[ZRNetworkTool sharedTool] InitiateDynamicCommentWithDict:dict.copy WithBlock:^(BOOL success, id responseData) {
                
                if (success) {
                    
                    [self.textField resignFirstResponder];
                    self.textField.text = @"";
                    self.textField.placeholder = @"我来说两句~";
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              [self loadData];
                                                                              
                                                                              
                                                                              self.pid = self.ID;
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"评论不能为空"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }else if (self.topicID){
        
        if (self.textField.text.length > 0) {
            
            NSMutableDictionary * dict = [NSMutableDictionary dictionary];
            
            [dict setValue:self.topicID forKey:@"topic_id"];
            [dict setValue:self.textField.text forKey:@"content"];
            [dict setValue:self.pid forKey:@"pid"];
            
            [[ZRNetworkTool sharedTool] userCommentTopicWithDict:dict.copy WithBlock:^(BOOL success, id responseData) {
                
                //            NSLog(@"res===%@",responseData);
                if (success) {
                    
                    [self.textField resignFirstResponder];
                    self.textField.text = @"";
                    self.textField.placeholder = @"我来说两句~";
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              [self loadData];
                                                                              
                                                                              
                                                                              self.pid = [NSString stringWithFormat:@"%@",self.fatherModel.pid];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"评论不能为空"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    
}


- (void)clickNameWithUsr_id:(NSString *)user_id{
        
    HiddenBar;
    PersonalViewController * personVC = [PersonalViewController new];
    
    personVC.ID = user_id;
    
    [self.navigationController pushViewController:personVC animated:YES];
}

@end
